﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Enterprise;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Department
{
    /// <summary>
    /// 添加部门信息
    /// </summary>
    public class CreateDepartmentHandler : IRequestHandler<CreateDepartmentCommand, Result>
    {
        /// <summary>
        /// 部门仓储
        /// </summary>
        private readonly IBaseRepository<Departments> _departmentRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateDepartmentHandler> _logger;

        /// <summary>
        /// mapper类
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public CreateDepartmentHandler(IBaseRepository<Departments> departmentRepository,
                                       ILogger<CreateDepartmentHandler> logger,
                                       IMapper mapper)
        {
            _departmentRepository = departmentRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(CreateDepartmentCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //查询部门信息是否存在
                var query = await (await _departmentRepository.GetAll()).Where(d => d.DepartmentName == request.DepartmentName).CountAsync();
                if (query > 0)
                {
                    result.Msg = "该部门已存在,请重新输入";
                }
                else
                {
                    //将条件转换成类
                    Departments depart = _mapper.Map<Departments>(request);
                    //添加数据
                    var res = await _departmentRepository.Add(depart);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "部门添加成功";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Msg = "添加部门异常" + ex.Message;
                _logger.LogError("添加部门异常" + ex.Message);
            }
            return result;
        }
    }
}
